/**
 * 
 */
package com.iwords.web.action;

/**
 * @author       BOLIN.HBC 
 * @time         2011-3-6    
 * @description  用户的操作SERVLET       
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.constants.Constants;
import com.iwords.enums.KnownLevel;
import com.iwords.service.AccountServiceLocal;
import com.iwords.service.SysLibServiceLocal;
import com.iwords.service.UserServiceLocal;
import com.iwords.service.object.AccountEntity;
import com.iwords.service.object.FeedbackEntity;
import com.iwords.service.object.SysLibEntity;
import com.iwords.service.object.UserEntity;
import com.iwords.service.object.UserSysConfigEntity;
import com.iwords.service.object.UserVacation;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.DateUtils;
import com.iwords.utils.Md5;
import com.iwords.utils.NumberUtils;
import com.iwords.utils.StringUtils;
import com.iwords.web.base.BaseAction;

@WebServlet(name = "userAction", urlPatterns = {"/user"})
public class UserAction extends BaseAction<UserEntity> {

    private static final long serialVersionUID = 1L;
    @EJB
    UserServiceLocal userService;
    @EJB
    SysLibServiceLocal sysLibService;
    @EJB
    AccountServiceLocal accountService;

    public void doProcess(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        String action = req.getParameter("action");

        if (Constants.REGISTER_ACTION.equals(action)) {
            doRegister(req, res);
        } else if (Constants.FIND_ACTION.equals(action)) {
            doFind(req, res);
        } else if (Constants.LOGIN_ACTION.equals(action)) {

            doLogin(req, res);
        } else if (Constants.UPDATE_ACTION.equals(action)) {

            doUpdate(req, res);

        } else if (Constants.ACCOUNT_ACTION.equals(action)) {
            doAccount(req, res);
        } else if (Constants.LATEST_FEEDBACK.equals(action)) {
            doFindLatestFeedbacks(req, res);
        } else if (Constants.LOGOUT_ACTION.equals(action)) {
            doLogout(req, res);
        } else if (Constants.DELAY_VACATION.equals(action)) {
            doDelayVacation(req, res);
        } else if (Constants.SAVE_USER_SYSCONFIG.equals(action)) {
            doSaveUserSysConfig(req, res);
        } else if (Constants.GETCONFIG_SYSCONFIG.equals(action)) {
            doGetUserSysConfig(req, res);
        }

    }

    private void doGetUserSysConfig(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        int batch_number = 20;
        // 首先获取设置了多少个单词背诵

        UserEntity user = userService.find(this.getUserId(req));
        List<UserSysConfigEntity> list = user.getUserSysConfigs();
        for (UserSysConfigEntity u : list) {
            if ("batch_number".equals(u.getConfigkey())) {
                if(u.getConfigvalue()!=null&&!u.getConfigvalue().isEmpty()){
                batch_number = Integer.parseInt(u.getConfigvalue());
                }

            }
        }
        req.setAttribute("userNumberConfig", batch_number);
        this.forward(req, res, Constants.ACCOUNT_SETTING_JSP);
    }

    private void doSaveUserSysConfig(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {

        UserEntity user = initEntity(req);
        JSONObject result = new JSONObject();
        UserSysConfigEntity sysConfig = new UserSysConfigEntity();
        sysConfig.setConfigkey("batch_number");
        if (req.getParameter("userWordNumber") != null || req.getParameter("userWordNumber").trim().length() > 0) {
            sysConfig.setConfigvalue(req.getParameter("userWordNumber").trim());
        } else {
            this.sendRedirect(req, res, Constants.ERROR_PAGE_JSP, null);
        }

        user.addSysConfig(sysConfig);

        if (userService.updateUserSysConfig(user)) {
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("系统错误，请稍候重试"));
        }

        this.sendRedirect(req, res, "sysLib?action=list", null);
    }

    private void doDelayVacation(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        UserEntity user = initEntity(req);
        JSONObject result = new JSONObject();

        if (userService.updateUserVacation(user, NumberUtils.stringToInt(req.getParameter("delayDays"), 0))) {
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        } else {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("修改用户有效期失败，请稍候重试"));
        }
        jsonPrint(res, result);
    }

    public void doLogin(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        UserEntity user = initEntity(req);
        
        
        try {
            user = userService.findUser(user);
            if (user != null) {
                SysLibEntity currentLib = null;

                if (user.getCurrentlib() != null) {
                    currentLib = sysLibService.findSysLibById(user.getCurrentlib());
                    currentLib.setPercent(sysLibService.getStudyLibNum(user.getUserid(), user.getCurrentlib(), KnownLevel.Known.getValue()) * 100
                            / currentLib.getQuantity());
                }
                req.setAttribute("currentLib", currentLib);
                req.getSession().setAttribute("user", user);

                if (req.getParameter("isRemember") != null) {
                    Cookie c = new Cookie("userid", user.getUserid() + "");
                    c.setMaxAge(60 * 60 * 24 * 365);
                    c.setPath("/");
                    res.addCookie(c);
                }
                this.forward(req, res, Constants.INDEX_PAGE_JSP);

            } else {
                req.setAttribute("error", "帐号或者密码错误,请重新登录");
                this.forward(req, res, Constants.LOGIN_PAGE_JSP);
            }
        } catch (Exception e) {
            System.out.print(e);
            log.error("login ereror!", e);
            this.forward(req, res, Constants.LOGIN_PAGE_JSP);

        }

    }

    public void doLogout(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        removeUser(req, res);
        this.sendRedirect(req, res, Constants.INDEX_PAGE_JSP, null);

    }

    public void doUpdate(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        UserEntity user = initEntity(req);
        try {
            user.setUserid(this.getUserId(req));
            userService.edit(user);
            user = userService.find(this.getUserId(req));
            req.getSession().setAttribute("user", user);
            this.sendRedirect(req, res, "user?action=account", null);
        } catch (Exception e) {
            this.sendRedirect(req, res, Constants.ERROR_PAGE_JSP, "更改用户信息失败!");
        }
    }

    private void doFindLatestFeedbacks(HttpServletRequest req, HttpServletResponse res) throws JSONException, IOException {
        JSONObject result = new JSONObject();

        try {
            List<FeedbackEntity> list = userService.findLatestFeedbacks();
            result.put(Constants.IS_SUCCESS, Boolean.TRUE);

            JSONArray defaultValue = new JSONArray();
//			JSONObject defaultValue = new JSONObject();
            for (FeedbackEntity feedback : list) {
                JSONObject re = new JSONObject();
                re.put("comments", feedback.getComments());
                //re.put("comments0", CodeUtils.encode(feedback.getComments()));

                re.put("responses", feedback.getResponses());
                re.put("username", feedback.getUser().getUsername());
                re.put("createtime", DateUtils.getDateStr(feedback.getCreatetime()));
                defaultValue.put(re);
            }

            result.put(Constants.DEFAULT_VALUE, defaultValue);
        } catch (Exception e) {
            log.error("feedbacks error!", e);
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询反馈信息失败"));
        }
    }

    public void doAccount(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {
        // 获取流水号
        List<AccountEntity> accounts = accountService.getAccountListByUserId(this.getUserId(req));
        req.setAttribute("accounts", accounts);
        this.forward(req, res, Constants.ACCOUNT_PAGE_JSP);

    }

    public void doRegister(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        this.removeUser(req, res);
        UserEntity user = initEntity(req);

        StringBuilder error = new StringBuilder();
        if (!StringUtils.isNotBlank(user.getUsername())) {
            error.append("用户名不能为空,");

        }
        if (!StringUtils.isNotBlank(user.getPassword())) {
            error.append("用户密码不能为空,");

        }
        if (!StringUtils.isNotBlank(user.getNickname())) {
            error.append("用户昵称不能为空,");

        }
        if (userService.isContain(user)) {

            error.append("该用户已经存在,");
        }
        if (error.length() == 0) {
            try {

                Date now = new Date();
                user.setCreatetime(now);
                user.setUpdatetime(now);
                UserVacation userVacation = new UserVacation();
                user.setUserVacation(userVacation);
                userVacation.setUser(user);
                userVacation.setCreatetime(now);
                userVacation.setUpdatetime(now);
                userVacation.setVacationCount(7L);// 默认7天年假
                userVacation.setExpireDate(DateUtils.getFormatDateTime(DateUtils.getFormatDateTime(DateUtils.getDateBeforeOrAfter(now, 7), "yyyyMMdd")
                        + " 23:59:59", "yyyyMMdd hh:mm:ss"));

                userService.create(user);

                user = userService.findUser(user);
                req.getSession().setAttribute("user", user);
                //增加cookie
                res.addCookie(new Cookie("userid", user.getUserid() + ""));
                this.sendRedirect(req, res, Constants.INDEX_PAGE, null);
            } catch (Exception e) {
                log.error("register error", e);
                this.sendRedirect(req, res, Constants.ERROR_PAGE_JSP, null);
            }

        } else {
            req.setAttribute("error", error.substring(0, error.length() - 1));
            this.forward(req, res, Constants.PAGE_REGISTER_JSP);

        }

    }

    public void doFind(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, JSONException {

        JSONObject result = new JSONObject();
        result.put(Constants.IS_SUCCESS, Boolean.TRUE);
        UserEntity user = initEntity(req);
        try {
            user = userService.find(user.getUserid());
            if (user != null) {
                JSONObject dedaultValue = new JSONObject();
                dedaultValue.put("username", user.getUsername());
                dedaultValue.put("nickname", user.getNickname());
                dedaultValue.put("birthday", user.getBirthday());
                dedaultValue.put("gender", user.getGender());
                result.put("defaultValue", dedaultValue);
            } else {
                result.put(Constants.IS_SUCCESS, Boolean.FALSE);
                result.put(Constants.MESSAGE, CodeUtils.encode("该用户不存在"));

            }
        } catch (Exception e) {
            result.put(Constants.IS_SUCCESS, Boolean.FALSE);
            result.put(Constants.MESSAGE, CodeUtils.encode("查询用户失败"));
        }

    }

    public UserEntity initEntity(HttpServletRequest req) {

        UserEntity user = new UserEntity();
        String userid = req.getParameter("userid");
        if (StringUtils.isNotBlank(userid)) {

            user.setUserid(Long.parseLong(req.getParameter("userid")));
        } else {
            user.setUserid(this.getUserId(req));
        }
        user.setUsername(req.getParameter("username"));
        user.setPassword(Md5.compute(req.getParameter("password")));
        user.setNickname(req.getParameter("nickname"));
        user.setPhone(req.getParameter("phone"));
        user.setQq(req.getParameter("qq"));
        user.setEmail(req.getParameter("email"));
        user.setGender(req.getParameter("gender"));
        String birthday = req.getParameter("birthday");
        if (StringUtils.isNotBlank(birthday)) {

            user.setBirthday(DateUtils.getDate_yyyyMMdd(birthday));
        }
        return user;

    }
}
